<template>
  <div class="Search">
    <div class="container" :style="{border: editModel ? '.1rem solid #fff' : '', background: editModel ? '#00000088' : ''}"
         @mouseenter="inContainer = true" @mouseleave="inContainer = false">
      <!--      选择搜索源-->
      <div :class="['select-region', changingSource||editModel ? 'changing-source' : '']" @mouseleave="changeSourceBlurHandle">
        <div :class="['item', item.name === currentSource ? 'currentSource' : '', editModel ? 'editModel' : '']"
             v-for="(item) in searchEngineList" :key="item.name"
             @click="changeSource(item)" @dblclick="setDefaultSource(item.name)" :title="item.name"
        >
          <div style="padding: .2rem" v-if="item.name === currentSource || changingSource || editModel">
<!--            <img style="height: 2rem" :src="item.icon" :alt="item.name">-->
            <el-image style="height: 2rem; width: 2rem; color: #cccccc" :src="item.icon" :key="item.name">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </div>
        <div key="add" class="item" v-if="editModel" @click="addSearchVisible = true"><i class="el-icon-plus"></i></div>
      </div>

      <!--      输入框-->
      <transition-group name="input" class="searchRegion">
        <input key="input" id="inputRegion" class="my-input" type="text" v-model="keyword"
               @focus="setFocused(true)" @blur="setFocused(false)" @keydown.esc.prevent="inputEsc"
               @keydown.enter="query(keyword)" :placeholder="currentSource" autocomplete="on" @keyup="keywordChangeHandle"
               @keydown.down="selectNextSug" @keydown.up.prevent="selectPrevSug" @keydown.tab.exact.prevent="changeToNextSrc"
               @keydown.tab.shift.prevent="changeToPrevSrc" :disabled="editModel"
        >
        <div key="clear" class="clear" :style="{color: focused ? '#000000' : '#ffffff'}" v-if="keyword" @click="clear"><i class="el-icon-close"></i></div>
        <div key="btn" class="my-search" v-if="keyword" @click="query(keyword)">
          <i class="el-icon-search"></i>
          </div>
        <!--      输入建议框-->
        <div class="suggestion-box" v-if="keyword && focused && suggestions.length"  key="suggestion">
          <div :class="['suggestion-item', item.active ? 'active' : '']" v-for="(item, index) in suggestions" :key="index"
               @mouseenter="item.active = true" @mouseleave="item.active = false"
               @click="query(item.content)">
            {{ item.content }}
          </div>
        </div>
      </transition-group>
    </div>
    <el-dialog title="添加搜索源" append-to-body :visible.sync="addSearchVisible">
      <el-form :model="searchForm">
        <el-form-item label="名称">
          <el-input v-model="searchForm.name"></el-input>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="searchForm.url" placeholder="例如：https://www.baidu.com/s?wd="></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSearch">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import searchEngineList from '@/views/searchEngineList'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      keywordCopy: '',
      searchEngineList: {},
      currentSource: '百度',
      addSearchVisible: false,
      searchForm: {
        name: '',
        url: ''
      },
      // 信息框
      info: null,
      // 搜索建议
      suggestions: [],
      // 鼠标是否在Container
      inContainer: false,
      changingSource: false
    }
  },
  props: ['editModel'],
  computed: {
    ...mapState(['focused'])
  },
  mounted () {
    document.getElementById('inputRegion').focus()
    // 选中哪个搜索源
    const source = window.localStorage.getItem('searchSource')
    if (source) {
      this.currentSource = source
    }
    this.suggestion()
    // 获取本地保存的搜索源
    this.unionSearch()
  },
  methods: {
    ...mapMutations(['setFocused']),
    suggestion () {
      window.baidu = {}
      window.baidu.sug = (data) => {
        const arr = []
        data.s.forEach(x => {
          arr.push({
            content: x,
            active: false
          })
        })
        this.suggestions = arr
      }
    },
    query (keyword) {
      const urlFn = this.searchEngineList.find(x => x.name === this.currentSource).urlFn
      window.open(urlFn(keyword), '_blank')
    },
    selectNextSug () {
      if (this.suggestions.length === 0) {
        return
      }
      const index = this.suggestions.findIndex(x => x.active)
      if (index === -1) {
        this.keywordCopy = this.keyword
        this.keyword = this.suggestions[0].content
        this.suggestions[0].active = true
        return
      }
      if (index === this.suggestions.length - 1) {
        this.keyword = this.keywordCopy
      } else {
        this.suggestions[index + 1].active = true
        this.keyword = this.suggestions[index + 1].content
      }
      this.suggestions[index].active = false
    },
    selectPrevSug () {
      if (this.suggestions.length === 0) {
        return
      }
      const index = this.suggestions.findIndex(x => x.active)
      if (index === -1) {
        this.keywordCopy = this.keyword
        this.keyword = this.suggestions[this.suggestions.length - 1].content
        this.suggestions[this.suggestions.length - 1].active = true
        return
      }
      if (index === 0) {
        this.keyword = this.keywordCopy
      } else {
        this.suggestions[index - 1].active = true
        this.keyword = this.suggestions[index - 1].content
      }
      this.suggestions[index].active = false
    },
    unionSearch () {
      this.searchEngineList = []
      let searchList = JSON.parse(window.localStorage.getItem('searchList'))
      if (!searchList) {
        searchList = []
      }
      searchList.forEach(item => {
        const arr = item.url.split('/')
        item.icon = arr[0] + '//' + arr[2] + '/favicon.ico'
        item.urlFn = (keyword) => item.url + keyword
      })
      this.searchEngineList = searchEngineList.concat(searchList)
    },
    changeSource (item) {
      if (this.editModel) {
        this.$confirm(`是否删除${item.name}？<br />${item.url}`, {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true
        }).then(() => {
          const searchList = JSON.parse(window.localStorage.searchList)
          const index = searchList.findIndex(x => x.name === item.name)
          if (index !== -1) {
            searchList.splice(index, 1)
          }
          window.localStorage.searchList = JSON.stringify(searchList)
          this.unionSearch()
          this.currentSource = this.searchEngineList[0].name
          this.$message.success(`删除${item.name}成功`)
        })
        return
      }
      document.getElementById('inputRegion').focus()
      this.changingSource = !this.changingSource
      this.currentSource = item.name
    },
    setDefaultSource (key) {
      window.localStorage.setItem('searchSource', key)
      this.$message.success(`设置默认搜索源为${key}`)
    },
    clear () {
      this.keyword = ''
      document.getElementById('inputRegion').focus()
    },
    addSearch () {
      let searchList = JSON.parse(window.localStorage.getItem('searchList'))
      if (!searchList) {
        searchList = []
      }
      let {
        name,
        url
      } = this.searchForm
      if (!url.startsWith('http')) {
        url = 'https://' + url
      }
      const index = searchList.findIndex(x => x.name === name)
      if (index !== -1) {
        searchList[index].url = url
      } else {
        searchList.push({
          name,
          url
        })
      }
      window.localStorage.setItem('searchList', JSON.stringify(searchList))
      this.$message.success('添加成功')
      this.unionSearch()
      this.addSearchVisible = false
      // this.addSearchVisible = true
    },
    // 根据改变以后的输入框值获取建议数据
    keywordChangeHandle (e) {
      // console.log(e.key)
      const arr = ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Tab', 'Shift', 'End', 'Home',
        'PageUp', 'PageDown', 'CapsLock', 'NumLock', 'Insert']
      if (arr.includes(e.key)) {
        return
      }
      const newValue = this.keyword
      const body = document.querySelector('body')
      const dom = document.getElementById('bdSug_script')
      if (dom) {
        body.removeChild(dom)
      }
      if (newValue === '') {
        this.suggestions = []
        return
      }
      // 创建一个新的script
      const T = document.createElement('script')
      T.setAttribute('charset', 'gbk')
      T.src = 'https://suggestion.baidu.com/su?wd=' + encodeURIComponent(newValue)
      T.id = 'bdSug_script'
      document.body.appendChild(T)
    },
    changeToNextSrc () {
      let index = this.searchEngineList.findIndex(x => x.name === this.currentSource)
      const { length } = this.searchEngineList
      if (index === length - 1) {
        index = 0
      } else {
        index += 1
      }
      this.currentSource = this.searchEngineList[index].name
    },
    changeToPrevSrc () {
      let index = this.searchEngineList.findIndex(x => x.name === this.currentSource)
      const { length } = this.searchEngineList
      if (index === 0) {
        index = length - 1
      } else {
        index -= 1
      }
      this.currentSource = this.searchEngineList[index].name
    },
    inputEsc () {
      this.setFocused(false)
      document.getElementById('inputRegion').blur()
    },
    changeSourceBlurHandle () {
      if (this.editModel) {
        return
      }
      this.changingSource = false
    }
  },
  watch: {
  }
}
</script>

<style scoped lang="scss">
.Search {
  padding: 2rem;
  width: 100vw;
  .container {
    width: 50vw;
    padding: 4rem;
    border-radius: 1rem;
    transition: all ease .3s;
    position: relative;
    //&:hover {
    //  background: #00000088;
    //}
    .opacity {
      opacity: 0;
    }
  }

  .select-region {
    position: absolute;
    left: 5rem;
    top: 9.2rem;
    display: flex;
    flex-direction: column;
    z-index: 4;

    .item {
      cursor: pointer;
      color: #00000088;
      //padding: 1rem;
      border: 1px solid #ffffff00;
      font-size: 2rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .currentSource {
      position: absolute;
      top: -3.4rem;
      color: #ffffff;
    }
    .editModel {
      &:hover {
        border: #ffffff solid .1rem;
        background: #ff8888;
      }
    }
  }

  .changing-source {
    background: #ffffff;
    top: 9.6rem;
    left: 4rem;
    z-index: 8;
    border-bottom-left-radius: 1rem;
    border-bottom-right-radius: 1rem;
    .item {
      padding: .8rem;
      //&:hover {
      //  border: cornflowerblue .1rem solid;
      //}
    }
    .currentSource {
      top: -4.6rem;
      padding: .8rem;
      background: #ffffff;
      border-top-left-radius: 2rem;
      //border-top-right-radius: 2rem;
    }
  }

  .searchRegion {
    display: flex;
    position: relative;

    .my-input {
      margin-top: 1rem;
      width: calc(100% - 10rem);
      height: 4rem;
      border-radius: 2rem;
      border: .1rem solid #ffffff;
      outline: none;
      font-size: 1.6rem;
      padding: 0 4rem;
      background: #ffffff88;
      color: #ffffff;
      transition: all ease .3s;

      &:focus {
        background: #ffffff;
        color: #000000;

        &::-webkit-input-placeholder {
          color: #00000088;
        }
      }

      &::-webkit-input-placeholder {
        color: #ffffff88;
        font-style: italic;
      }
    }

    .my-search {
      margin-top: 1rem;
      height: 4rem;
      padding: 0 1rem;
      border-radius: 2rem;
      border: .1rem solid #ffffff;
      font-size: 2rem;
      background: #ffffff88;
      color: #ffffff;
      transition: all ease .3s;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 1rem;

      &:hover {
        cursor: pointer;
        background: cornflowerblue;
        //color: cornflowerblue;
      }
      div {
        width: max-content;
      }
    }

    .clear {
      cursor: pointer;
      position: absolute;
      right: 8rem;
      font-size: 2rem;
      top: 2rem;
      z-index: 3;
    }

    .suggestion-box {
      position: absolute;
      width: calc(100% - 10rem);
      padding-right: 4rem;
      font-size: 1.6rem;
      top: 5.2rem;
      border: .1rem solid #ffffff88;
      border-radius: 1rem;
      background: #cccccc;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
      z-index: 7;
      overflow-x: hidden;
      .suggestion-item {
        height: 3rem;
        width: 100%;
        //background: #000000;
        color: #000000;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 2rem;
        padding-right: 2rem;
        transition: all ease .1s;
      }
      .active {
        cursor: pointer;
        background: #ffffff;
        color: #000000;
        border-radius: .4rem;
      }

      //&::after {
      //  content: '';
      //  top: 0;
      //  left: 0;
      //  position: absolute;
      //  width: 100%;
      //  height: 100%;
      //  filter: blur(0);
      //  border-radius: .4rem;
      //  background: #cccccc88;
      //  z-index: -1
      //}
    }
    @media screen and (max-height: 700px) {
      .suggestion-box {
        max-height: 40vh;
        overflow-y: auto;
      }
    }
  }

  .input-enter-active, .input-leave-active {
    transition: all ease .3s;
  }

  .input-enter {
    opacity: 0;
    transition: all ease .3s;
    transform: translateX(-40px);
  }

  .input-leave-to {
    transition: all ease .3s;
    transform: translateX(-40px);
    opacity: 0;
  }
}
</style>
